package com.yanggu.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanggu.payment.entity.OrderInfo;
import com.yanggu.payment.entity.RefundInfo;
import com.yanggu.payment.mapper.RefundInfoMapper;
import com.yanggu.payment.service.OrderInfoService;
import com.yanggu.payment.service.RefundInfoService;
import com.yanggu.payment.util.OrderNoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @version V1.0
 * @author: YangGu
 * @date: 2022/5/7 14:47
 * @description:
 */
@Service
public class RefundInfoServiceImpl extends ServiceImpl<RefundInfoMapper, RefundInfo> implements RefundInfoService {

    @Autowired
    private OrderInfoService orderInfoService;

    @Override
    public RefundInfo createRefundInfo(String orderNo, String reason) {

        OrderInfo orderInfo = orderInfoService.queryByOrderNo(orderNo);
        if (orderInfo == null) {
            throw new RuntimeException("订单不存在" + orderNo);
        }

        LambdaQueryWrapper<RefundInfo> wrapper = Wrappers.<RefundInfo>lambdaQuery().eq(RefundInfo::getOrderNo, orderNo);

        RefundInfo refundInfo = baseMapper.selectOne(wrapper);
        if (refundInfo != null) {
            return refundInfo;
        }

        refundInfo = new RefundInfo();
        refundInfo.setOrderNo(orderNo);
        refundInfo.setRefundNo(OrderNoUtils.getRefundNo());
        refundInfo.setTotalFee(orderInfo.getTotalFee());
        refundInfo.setRefund(orderInfo.getTotalFee());
        refundInfo.setReason(reason);

        baseMapper.insert(refundInfo);

        return refundInfo;
    }
}
